<template>
  <div class="register_container">
    <div class="register_box">
      <div class="register_box_head">
        <h2 style="color: black;">用户注册</h2>
      </div>
      <div class="register_box_body">
        <el-tabs :stretch="true">
          <el-tab-pane label="账号密码注册">
            <el-form label-position label-width="0px" class="register_form" :model="registerForm" ref="registerFormRef"
              :rules="registerFormRules">
              <!-- 用户名 -->
              <el-form-item prop="username">
                <el-input placeholder="用户名" v-model="registerForm.username"></el-input>
              </el-form-item>
              <!-- 密码 -->
              <el-form-item prop="password1">
                <el-input type="password" show-password placeholder="密码" v-model="registerForm.password1"></el-input>
              </el-form-item>
              <el-form-item prop="r_password1">
                <el-input type="password" show-password placeholder="确认密码" v-model="registerForm.r_password1">
                </el-input>
              </el-form-item>
              <el-form-item prop="validatecode">
                <el-input placeholder="验证码" v-model="registerForm.validatecode">
                  <template #append class="validatecode">
                    <img alt="" @click="getValidatecode" :src="validatecodeImg" />
                  </template>
                </el-input>
              </el-form-item>
              <!-- 按钮区域 -->
              <el-form-item class="register_btns">
                <el-button type="primary" @click="registerByUsername">注册</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="邮箱注册">
            <!-- 邮箱验证登录表单 -->
            <el-form ref="emailRegisterFormRef" :model="emailRegisterForm" :rules="emailRegisterFormRules">
              <!-- 邮箱 -->
              <el-form-item prop="email">
                <el-input placeholder="邮箱" clearable v-model="emailRegisterForm.email">
                </el-input>
              </el-form-item>
              <!-- 密码 -->
              <el-form-item prop="password2">
                <el-input placeholder="密码" show-password v-model="emailRegisterForm.password2">
                </el-input>
              </el-form-item>
              <!-- 密码 -->
              <el-form-item prop="r_password2">
                <el-input placeholder="请再次输入密码" show-password v-model="emailRegisterForm.r_password2">
                </el-input>
              </el-form-item>
              <!-- 邮箱验证码 -->
              <el-form-item prop="emailCode">
                <el-input placeholder="验证码" v-model="emailRegisterForm.emailCode">
                  <template #append>
                    <el-button type="primary" :disabled="disabled" @click="getEmailRegisterValidateCode">{{buttonText}}
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
              <!-- 按钮区域 -->
              <el-form-item class="login_btns">
                <el-button type="primary" @click='regiseterByEmail'>注册</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script>
  import {
    onMounted,
    ref,
    reactive,
    toRefs,
    getCurrentInstance
  } from 'vue'
  import qs from 'qs'
  import axios from 'axios'
  export default {
    setup() {
      // 用户名注册密码的验证规则
      var checkPassword1 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== state.registerForm.password1) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      }
      // 用户名注册密码的验证规则
      var checkPassword2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== state.emailRegisterForm.password2) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      }
      const {
        proxy
      } = getCurrentInstance()
      const registerFormRef = ref(null)
      const emailRegisterFormRef = ref(null)
      const state = reactive({
        // 注册表单的数据绑定对象
        registerForm: {
          username: '',
          password1: '',
          r_password1: '',
          validatecode: ''
        },
        // 注册表单的验证规则
        registerFormRules: {
          username: [{
            required: true,
            message: '请输入你的昵称',
            trigger: 'blur'
          }],
          password1: [{
            required: true,
            message: '请输入你的密码',
            trigger: 'blur'
          }],
          r_password1: [{
              required: true,
              message: '请再次输入你的密码',
              trigger: 'blur'
            },
            {
              validator: checkPassword1,
              trigger: 'blur'
            }
          ],
          validatecode: [{
            required: true,
            message: '请输入验证码',
            trigger: 'blur'
          }]
        },
        emailRegisterForm: {
          email: '',
          password2: '',
          r_password2: '',
          emailCode: ''
        },
        emailRegisterFormRules: {
          email: [{
            required: true,
            message: '请输入你的昵称',
            trigger: 'blur'
          }],
          password2: [{
            required: true,
            message: '请输入你的密码',
            trigger: 'blur'
          }],
          r_password2: [{
              required: true,
              message: '请再次输入你的密码',
              trigger: 'blur'
            },
            {
              validator: checkPassword2,
              trigger: 'blur'
            }
          ],
          emailCode: [{
            required: true,
            message: '请输入验证码',
            trigger: 'blur'
          }]
        },
        validatecodeImg: '',
        loading: false,
        // 控制获取验证码
        buttonText: '获取验证码',
        disabled: false,
        duration: 60,
        timer: null
      })
      onMounted(() => { 
        getValidatecode()
      })
      // 获取验证码
      const getValidatecode = () => {
        axios.get(`http://back.cduestc.cc:8081/util/validateCode`, {
          responseType: 'blob'
        }).then(res => {
          localStorage.setItem('token', res.headers.token)
          let blob = new Blob([res.data], {
            type: "image/jpg"
          })
          var Fr = new FileReader()
          Fr.readAsDataURL(blob)
          Fr.onload = (event) => {
            state.validatecodeImg = event.target.result
          }
        })
      }
      // 用户名注册
      const registerByUsername = async () => {
        state.loading = true
        const obj = {
          username: state.registerForm.username,
          password: state.registerForm.r_password1,
          validateCode: state.registerForm.validatecode,
          token: localStorage.getItem('token')
        }
        try {
          const res = await new proxy.$request(proxy.$urls.m().registerByUsername, qs.stringify(obj)).modepost()
          console.log(res)
          if (res.data.success != true) {
            new proxy.$tips(res.data.message, 'warning').mess_age()
          } else {
            new proxy.$tips(res.data.message, 'success').mess_age()
            localStorage.setItem('token', res.data.data.token)
            // 成功跳转页面
          }
          state.loading = false
        } catch (e) {
          state.loading = false
          new proxy.$tips('服务器发生错误', 'error').mess_age()
        }
      }
      // 获取邮箱注册验证码
      const getEmailRegisterValidateCode = () => {
        const obj = {
          email: state.emailRegisterForm.email
        }
        axios.post('http://ganyujia.tpddns.cn:8081/user/getRegisterByEmailValidateCode', qs.stringify(obj)).then(
          res => {
            console.log(res)
            if (res.data.success != true) {
              new proxy.$tips(res.data.message, 'warning').mess_age()
            } else {
              new proxy.$tips(res.data.message, 'success').mess_age()
              // localStorage.setItem('token', res.data.data.token)
              // sessionStorage.setItem('jsessionid', res.headers.jsessionid)
              state.timer = setInterval(() => {
                state.disabled = true
                const tmp = state.duration--
                state.buttonText = `${tmp}秒后重新获取`
                if (tmp <= 0) {
                  clearInterval(state.timer)
                  state.duration = 60
                  state.buttonText = '重新获取验证码'
                  state.disabled = false
                }
              }, 1000)
            }
          })
      }
      const regiseterByEmail = async () => {
        state.loading = true
        const obj = {
          email: state.emailRegisterForm.email,
          password: state.emailRegisterForm.r_password2,
          emailValidateCode: state.emailRegisterForm.emailCode,
          token: localStorage.getItem('token')
        }
        try {
          const res = await new proxy.$request(proxy.$urls.m().regiseterByEmail, qs.stringify(obj)).modepost()
          if (res.data.success != true) {
            new proxy.$tips(res.data.message, 'warning').mess_age()
          } else {
            new proxy.$tips(res.data.message, 'success').mess_age()
            localStorage.setItem('token', res.data.data.token)
            sessionStorage.setItem('jsessionid', res.headers.jsessionid)
          }
          state.loading = false
        } catch (e) {
          state.loading = false
          new proxy.$tips('服务器发生错误', 'error').mess_age()
        }
      }
      return {
        ...toRefs(state),
        registerFormRef,
        emailRegisterFormRef,
        getValidatecode,
        registerByUsername,
        getEmailRegisterValidateCode,
        regiseterByEmail
      }
    }
  }
</script>

<style lang="less" scoped>
	.login_btns .el-button{
		background-color: #008aca;
		border: none;
	}
	
  .register_container {
    width: 100%;
    height: 100%;
    background: url(../assets/登录页面背景图.png);
    position: fixed;
    background-size: 100% 100%;
  }

  .register_box {
    width: 400px;
    height: 600px;
    background-color: rgba(225, 225, 225, 0);
    border: 1px solid rgba(225, 225, 225, 0);
    box-shadow: 2px 3px 3px #aaaaaa;
    border-radius: 3px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
  }

  .register_box_body {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 90%;
    padding: 0 20px;
    box-sizing: border-box;
  }

  el-form-item {
    width: 220px;
  }

  .validatecode {
    img {
      width: 100%;
      height: 100%;
    }
  }

  .register_btns {
    text-align: center;
	.el-button {
		color: black;
		background-color: #008aca;
		border: none;
	}
  }
</style>

<style scoped>
  .register_box { 
    backdrop-filter: blur(15px);
    box-shadow: 0 0 5px #fff;
  }
  
  .el-tabs >>> .el-tabs__item:hover {
      color: #fff;
      cursor: pointer;
  }
  
  .el-tabs >>> .el-tabs__item.is-active {
      color: rgb(17, 48, 91);
  }
  
  .el-input {
    --el-input-font-color: black;
  }
  
  .el-input>>>.el-input__inner {
    background-color: #c8f1ff!important;
    box-shadow: 0 0 2px #fff;
    border: 1px solid #fff;
  }
  
  .el-button {
    border-radius: 10px;
  }
  
  .el-button--primary {
    border: 1px solid #fff;
    box-shadow: 0 0 2px #fff;
    --el-button-font-color: #409e40;
    --el-button-background-color: #ffffff;
    --el-button-border-color: #409eff;
    --el-button-hover-color: #66b1ff;
    --el-button-active-font-color: #e6e6e6;
    --el-button-active-background-color: #0d84ff;
    --el-button-active-border-color: #0d84ff;
  }
</style>
